package com.cash.app.utils.extra

import android.content.Context
import android.content.Intent
import android.content.IntentFilter
import android.os.Build
import android.telephony.PhoneStateListener
import android.telephony.SignalStrength
import android.telephony.TelephonyManager
import androidx.annotation.RequiresApi
import com.cash.app.application.MyApplication
import com.cash.app.constant.AppConstant.K_GA_ID
import com.cash.app.utils.SpUtils
import com.cash.app.utils.extra.model.BatteryStatusData
import com.cash.app.utils.extra.tools.BatteryBroadcastReceiver
import com.cash.app.utils.extra.tools.GeneralUtils

object ExtraInfoUtils {
    var dbm: Int = 0

    /**
     * Battery information
     */
    private var _batteryStatusData: BatteryStatusData? = null
    var batteryStatusData: BatteryStatusData
        get() = _batteryStatusData ?: BatteryStatusData()
        set(value) {
            _batteryStatusData = value
        }

    var batteryBroadcastReceiver: BatteryBroadcastReceiver? = null

    var mRegisterTag: Boolean = false

    fun init() {
        initBroadcast()
        GeneralUtils.getGaid()
        dBM
    }

    fun getApp(): Context {
        return MyApplication.appContext
    }

    private fun initBroadcast() {
        batteryBroadcastReceiver = BatteryBroadcastReceiver()
        val intent = IntentFilter()
        intent.addAction(Intent.ACTION_BATTERY_CHANGED)
        MyApplication.appContext.registerReceiver(batteryBroadcastReceiver, intent)
        mRegisterTag = true
    }

    fun removeBroadcast() {
        if (mRegisterTag) {
            MyApplication.appContext.unregisterReceiver(batteryBroadcastReceiver)
            mRegisterTag = false
        }
    }


    val deviceId: String
        get() {
            return SpUtils.get(K_GA_ID, "")
        }


    val dBM: Unit
        get() {
            val tm: TelephonyManager =
                MyApplication.appContext.getSystemService(Context.TELEPHONY_SERVICE) as TelephonyManager
            val myPhoneListener: PhoneStateListener = object : PhoneStateListener() {
                @RequiresApi(api = Build.VERSION_CODES.M)
                override fun onSignalStrengthsChanged(signalStrength: SignalStrength) {
                    val level: Int = signalStrength.getLevel()
                    println("level==============$level")

                    val asu: Int = signalStrength.getGsmSignalStrength()
                    dbm = -113 + 2 * asu
                }
            }

            tm.listen(myPhoneListener, PhoneStateListener.LISTEN_SIGNAL_STRENGTHS)

            tm.listen(myPhoneListener, PhoneStateListener.LISTEN_NONE)
        }
}
